package com.viroyal.monitorlib;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.suntiago.baseui.utils.log.Slog;
import com.viroyal.monitorlib.entity.ApiConfig;
import com.viroyal.monitorlib.network.Api;
import com.viroyal.monitorlib.network.BaseRspObserver;
import com.viroyal.monitorlib.network.UpdateApi;
import com.viroyal.monitorlib.network.rsp.ApiResponse;
import com.viroyal.monitorlib.rxpermissions.RxPermissions;
import com.viroyal.monitorlib.service.MainStartService;
import com.viroyal.monitorlib.utils.SPUtils;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Time:2019/12/23
 * Author:bichao
 * description:
 */
public class StartMonitor {
    private static final String TAG = "StartMonitor";
    private Context context;
//    private AlertDialog alertDialog;
    private String[] permissionsRequired = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private int mAPITime = 1000*10;

    public StartMonitor(Context context) {
        this.context = context;
    }

    public void init() {
//        alertDialog = new AlertDialog.Builder(context)
//                .setTitle("配置加载")
//                .setCancelable(false)
//                .setMessage("正在加载配置信息...")
//                .create();
//        alertDialog.show();
        permisstion();
        initData(false);
    }

    private void permisstion() {
        RxPermissions.getInstance(context)
                //传入数组，也可以使用不定长参数，多个权限用","隔开
                .request(permissionsRequired)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        //当所有权限都允许之后，返回true
                        getApi();
                    }
                });
    }

    private void getApi() {
        String school_id = com.suntiago.baseui.utils.SPUtils.getInstance(context).get("school_id", "1000");
        Slog.d(TAG, "getApi: school_id" + school_id);
        Api.get().getApi2(UpdateApi.class)
                .api(Api.get().getDeviceId(context),school_id, "JianKong")
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseRspObserver<>(ApiResponse.class, rsp -> {
                    if (rsp.error_code == 1000) {
                        Slog.d(TAG, "call [rsp]:"+rsp.apiModel.config);
//                        alertDialog.dismiss();
                        Log.e("api_config", SPUtils.getInstance(context).get("api_config"));
                        if (!SPUtils.getInstance(context).get("api_config").equals(rsp.apiModel.config)) {
                            Slog.d(TAG, "call:" + rsp.apiModel.config);
                            Gson gson = new Gson();
                            ApiConfig ac = gson.fromJson(rsp.apiModel.config, ApiConfig.class);
                            Slog.d(TAG, "call:api:" + ac.api);
                            SPUtils.getInstance(context).put("MonitorIp", ac.api + "/");
                            SPUtils.getInstance(context).put("api_config", rsp.apiModel.config);
                            SPUtils.getInstance(context).put("mac",Api.get().getDeviceId(context));
                            SPUtils.getInstance(context).put("school_id",ac.school_id);
                            initData(true);
                        }
                    } else {
                        if (!TextUtils.isEmpty(SPUtils.getInstance(context).get("MonitorIp"))
                                &&!SPUtils.getInstance(context).get("MonitorIp").equals("http://:8000/")){
//                            alertDialog.dismiss();
                            Slog.d(TAG, "apiCallback:");
                        }else{
                            Observable.timer(mAPITime, TimeUnit.MILLISECONDS).subscribe((v) -> {
                                Slog.d(TAG, "Observable.timer:regetApi");
                                getApi();
                            });
                        }
                    }
                }));
    }

    private void initData(boolean apichanged) {
        Slog.d(TAG, "init:");
        String apiConfig = SPUtils.getInstance(context).get("api_config");
        Slog.d(TAG, "init:apiConfig:"+apiConfig);
        if (!apiConfig.equals("")) {
            Gson gson = new Gson();
            ApiConfig ac = gson.fromJson(apiConfig, ApiConfig.class);
            Api.get().setApi(ac.api + "/");
            Api.get().setApiConfig(ac.api + "/", ac.netty_host, ac.netty_port, ac.school_id);
            Slog.d(TAG, "init:apiHost:"+Api.DEFAULT_HOST);
            Api.init(context);
            Intent intent = new Intent(context, MainStartService.class);
            if (apichanged){
                intent.putExtra("apichanged",1);
            }
            context.startService(intent);
        }
    }
}
